package controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sql.UserStoryDao;
import beans.UserStoryBean;

/**
 * Servlet implementation class EditUserStory
 */
@WebServlet("/EditUserStory")
public class EditUserStory extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditUserStory() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserStoryBean userStoryBean = new UserStoryBean();
		userStoryBean.setId(0);
		userStoryBean.setName(request.getParameter("user-story-name"));
		userStoryBean.setDescription(request.getParameter("user-story-description"));
		userStoryBean.setType(1);
		userStoryBean.setStoryPoints(null);

		try {
			String storyPointsParameter = request.getParameter("user-story-story-points");
			if (! storyPointsParameter.isEmpty()) {
				userStoryBean.setStoryPoints(Integer.parseInt(storyPointsParameter));
			}
			userStoryBean.setId(Integer.parseInt(request.getParameter("user-story-id")));
			userStoryBean.setType(Integer.parseInt(request.getParameter("user-story-type")));
		}
		catch (NumberFormatException e) {
			e.printStackTrace();
		}

		UserStoryDao userStoryDao = new UserStoryDao();
		try {
			userStoryDao.update(userStoryBean);
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
		
		// return data
		PrintWriter out = response.getWriter();
		out.write(userStoryBean.getJson());
	}

}
